// pages/afterSaleCente/afterSaleCente.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    type: 0,
    choose:0,
    count:1,
    chooseCard:0,
    choo_modal: "none"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //获取手机高度
    this.setData({
      navH: app.globalData.navHeight,
      balance: wx.getStorageSync("balance")
    })
    wx.request({
      url: app.globalData.url + 'getBuyStoredValueCardPageData',
      method: 'GET',
      data: {

      },
      success: function (res) {
        console.log(res.data.data)
        that.setData({
          ImageList:res.data.data.advertisingList,
          storedValueCardList: res.data.data.storedValueCardList,
          price: res.data.data.storedValueCardList[0].price
        });
      },
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  navBack: function () {
    wx.navigateBack({
    })
  },
  toDetail: function () {
    var that = this;
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?productid=' + that.data.product.product.productId,
    })
  },
  add: function () {
    var count  = this.data.count;
    count++;
    this.setData({
      count:count,
      price: this.data.storedValueCardList[this.data.chooseCard].price*count
    })
  },
  reduce: function () {
    var count = this.data.count;
    count--;
    if(count>0){
      this.setData({
        count: count,
        price: this.data.storedValueCardList[this.data.chooseCard].price * count
      })
    }
  },
  chooseThisCard: function (e) {
    if (this.data.chooseCard != e.currentTarget.dataset.index){
      this.setData({
        count:1,
        price: this.data.storedValueCardList[e.currentTarget.dataset.index].price,
        chooseCard: e.currentTarget.dataset.index
      })
    }
  },
  goMyCard: function () {
    wx.navigateTo({
      url: '/pages/myStoredValue/myStoredValue'
    })
  },
  getCurrent:function(e){
    var cur = e.detail.current;    //有兴趣的小伙伴可以打印e,瞅瞅它长啥样
    this.setData({
      choose: cur
    })
 },
 
  // 弹出
  modal_s: function (e) {
    this.setData({
      choo_modal: "block"
    });
  },
  //消失
  modal_n: function () {
    this.setData({
      choo_modal: "none"
    });
  },
  buy: function(e) {
    var that = this;
    this.setData({
      choo_modal: "none"
    });
    /**充值 */
    var that = this;
    var userid = wx.getStorageSync("userId");
    var price = that.data.price;
    var img = that.data.ImageList[that.data.choose].imageURL
    var cardList = '['
    for (var i = 0; i < that.data.count;i++){
      cardList += '{"cardId":' + that.data.storedValueCardList[that.data.chooseCard].cardId + ',"num":1},'
    }
      cardList = cardList.substring(0,cardList.length-1);
      cardList +=']';
    wx.showLoading({
      title: '正在提交...',
      icon: 'loading',
    })
    wx.request({
      url: app.globalData.url + 'buyStoredValueCard',
      method: "POST",
      data: {
        userId: userid,
        cardFace: img,
        payChannel: parseInt(e.currentTarget.dataset.type),
        cardList: cardList
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var data = res.data.data;
        console.log(res.data);

        if (res.data.result == 0) {
          wx.hideLoading();
          wx.showToast({
            title: res.data.errmsg,
            icon: 'none'
          })

          return;
        }
        that.setData({
          orderid: data.orderId,
        })
        if (data.orderStatus != 7001) {
          // that.modal_s();
          that.setData({
            userId: wx.getStorageSync("userId"),
            orderId: data.orderId,
          })
          wx.request({
            url: app.globalData.url + 'getOrderWeixinPrepayId',
            data: {
              userId: wx.getStorageSync("userId"),
              orderId: data.orderId,
              orderNumber: data.orderNumber,
            },
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              var resultData = res.data;
              var hisId = resultData.hisId;
              if (res.data.result != 1 && res.data.result != 9) {
                wx.showToast({
                  title: "数据异常，请稍后重试",
                  icon: 'none'
                })
                return;
              }
              wx.requestPayment({
                'timeStamp': resultData.timeStamp,
                'nonceStr': resultData.nonceString,
                'package': resultData.packageStr,
                'signType': resultData.signType,
                'paySign': resultData.sign,
                //支付成功
                success: function (res) {
                  if ("requestPayment:ok" === res.errMsg) {
                    wx.showToast({
                      title: '支付成功',
                      icon: 'success',
                      duration: 2000,
                      success: function () {
                        if (that.data.type == 2) {
                          console.info(that.data.orderid);
                          wx.navigateTo({
                            url: '/pages/assembleDetail/assembleDetail?orderId=' + that.data.orderid + '&back=1'
                          })
                        } else {
                          console.info(that.data.lipinka);
                          if (that.data.lipinka != 3) {
                            wx.navigateTo({
                              url: '/pages/paySeccess/paySeccess?orderId=' + that.data.orderid + '&back=1'
                            })
                          } else {
                            wx.navigateTo({
                              url: '/pages/giftCardBuySuccess/giftCardBuySuccess?orderId=' + that.data.orderid + '&back=1'
                            })
                          }

                        }

                      }
                    })
                  }
                },
                //支付或者取消失败
                fail: function (res) {
                  if ("requestPayment:fail cancel" === res.errMsg) {
                    wx.showToast({
                      title: '取消支付',
                      icon: 'none',
                      duration: 2000,
                      success: function () {
                        if (that.data.type == 2) {
                          wx.request({
                            url: app.globalData.url + 'delOrder',
                            method: 'GET',
                            data: {
                              orderId: that.data.orderid,
                              userId: wx.getStorageSync("userId")
                            },
                          });
                        } else {
                          wx.showToast({
                            title: "取消支付",
                            icon: 'none'
                          })
                          // wx.navigateBack({
                          //   delta: 1,
                          // });
                          // setTimeout(function () {
                          //   wx.navigateBack({
                          //     delta: 1,
                          //   });
                          // }, 2000) //延迟时间
                        }

                      }
                    })
                  } else {

                    wx.showToast({
                      title: "支付失败",
                      icon: 'none'
                    })
                  }
                },
              })
            }
          })
        } else if (res.data.result == 1 && res.data.data.orderStatus == 7001) {
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 2000,
            success: function () {
              console.log('haha');
              wx.navigateTo({
                url: '/pages/paySeccess/paySeccess?orderId=' + that.data.orderid + '&back=1'
              })
            }
          })
        }
      }
    });
  },
  
})